from flask import Flask,jsonify
from flask import render_template
from datetime import datetime
import pandas as pd
import json
import jieba
import collections #计算词频专用

app = Flask(__name__)


@app.route('/gettime')
def get_time():
    return str(datetime.now()).split('.')[0]

@app.route('/',methods=['Get','Post'])
def control():
    return render_template('main.html')

@app.route('/getdata')
def get_data():
    df = pd.read_csv('data/other.csv')
    data = {}
    #累计死亡
    data['dead'] = df.iloc[-1]['dead']
    #累计确诊
    data['confirm'] = df.iloc[-1]['confirm']
    #剩余疑似
    data['suspect'] = df.iloc[-1]['suspect']
    #累计治愈
    data['heal'] = df.iloc[-1]['heal']
    return data

@app.route('/m2')
def get_m2data():

    with open('./data/detail.json','r') as f:
        d = json.load(f)
    result = {}
    res = []
    for data in d['areaTree'][0]['children']:
        d = {}
        d['name'] = data['name']
        d['value'] =data['total']['confirm']
        res.append(d)
    result['data'] = res
    return result

@app.route('/l1')
def get_l1data():
    df = pd.read_csv('data/other.csv')
    data = {}
    data['date_list'] = list(df['date'])
    #累计死亡
    data['dead_list'] = list(df['dead'])
    #累计确诊
    data['confirm_list'] = list(df['confirm'])
    #剩余疑似
    data['suspect_list'] = list(df['suspect'])
    #累计治愈
    data['heal_list'] = list(df['heal'])
    return jsonify(data)

@app.route('/l2')
def get_l2data():
    print('进入l2')
    df = pd.read_csv('data/chinaDayAdd.csv')
    data = {}
    data['date_list'] = list(df['date'])
    #新增确诊
    data['new_confirm_list'] = list(df['confirm'])
    #新增疑似
    data['new_suspect_list'] = list(df['suspect'])
    return jsonify(data)

@app.route('/r1')
def get_r1data():
    print('进入r1')
    with open('data/detail.json', 'r') as f:
        d = json.load(f)
    result = {}
    l = []
    for data in d['areaTree'][0]['children']:
        for d2 in data['children']:
            s = {}
            if '待' not in d2['name'] and '输入' not in d2['name']:
                s['city'] = d2['name']
                s['nowconfirm'] = d2['total']['nowConfirm']
                l.append(s)
    df = pd.DataFrame(l).sort_values(by='nowconfirm',ascending=False).iloc[1:6]
    result['city_list'] = list(df['city'])
    result['confirm_list'] = list(df['nowconfirm'])
    return result


@app.route('/r2')
def get_r2data():
    with open('data/hot_title.txt','r',encoding='utf-8') as f:
        d = f.read()
    cut_list = jieba.cut(d, cut_all = False)
    word_counts = collections.Counter(cut_list)#计算词频
    
    l = []
    for i,j in word_counts.items():
        s = {}
        s['name'] = i
        s['value'] = j
        l.append(s)
    result = {}
    result['data'] = l
    print("&&&&*****")
    return result
if __name__ == '__main__':
    app.run()